package com.peakmain.wanandroid.netmodule.net.http.params;


import com.peakmain.wanandroid.netmodule.net.http.OkHttpManager;
import com.peakmain.wanandroid.netmodule.net.http.RequestCall;
import com.peakmain.wanandroid.netmodule.net.http.callback.RequestCallBack;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * author ：Peakmain
 * version : 1.0
 * createTime：2020/2/22
 * mail:2726449200@qq.com
 * describe：http请求参数的基类
 */
public abstract class BaseRequest<T extends BaseRequest> {
    protected String url;
    protected Object tag;
    protected RequestParams mParams = new RequestParams();
    protected ParamsHeaders headers = new ParamsHeaders();
    protected int id;


    public BaseRequest() {
        //添加公共请求参数
        if (OkHttpManager.getInstance().getCommonParams() != null) {
            mParams.put(OkHttpManager.getInstance().getCommonParams());
        }
        if (OkHttpManager.getInstance().getCommonHeaders() != null) {
            headers.put(OkHttpManager.getInstance().getCommonHeaders());
        }
    }

    @SuppressWarnings("unchecked")
    public T url(String url) {
        this.url = url;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    public T tag(Object tag) {
        this.tag = tag;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    public T params(RequestParams params) {
        mParams = params;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    public T headers(ParamsHeaders headers) {
        if (headers == null) {
            return null;
        } else {
            this.headers.put(headers);
            return (T) this;
        }
    }

    public T headers(String key, String value){
        this.headers.put(key,value);
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    public T id(int id) {
        this.id = id;
        return (T) this;
    }

    public int getId() {
        return id;
    }


    /**
     * 通用的拼接请求头
     */
    protected Request.Builder appendHeaders(Request.Builder requestBuilder) {
        Headers.Builder headerBuilder = new Headers.Builder();
        ConcurrentHashMap<String, String> headerMap = headers.headersMap;
        if (headerMap.isEmpty()) return requestBuilder;
        for (String key : headerMap.keySet()) {
            headerBuilder.add(key, headerMap.get(key));
        }
        requestBuilder.headers(headerBuilder.build());
        return requestBuilder;
    }

    /**
     * 生成类是表单的请求体
     */
    protected RequestBody generateMultipartRequestBody() {
        if (mParams.fileParamsMap.isEmpty()) {
            //表单提交，没有文件
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            for (String key : mParams.urlParamsMap.keySet()) {
                bodyBuilder.add(key, mParams.urlParamsMap.get(key));
            }
            return bodyBuilder.build();
        } else {
            //表单提交，有文件
            MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            //拼接键值对
            if (!mParams.urlParamsMap.isEmpty()) {
                for (Map.Entry<String, String> entry : mParams.urlParamsMap.entrySet()) {
                    multipartBodybuilder.addFormDataPart(entry.getKey(), entry.getValue());
                }
            }
            //拼接文件
            for (Map.Entry<String, ArrayList<FileWrapper>> entry : mParams.fileParamsMap.entrySet()) {
                for (int i = 0; i < entry.getValue().size(); i++) {
                    FileWrapper fileWrapper = entry.getValue().get(i);
                    RequestBody fileBody = RequestBody.create(fileWrapper.mediaType, fileWrapper.file);
                    multipartBodybuilder.addFormDataPart(entry.getKey(), fileWrapper.fileName, fileBody);
                }
            }
            return multipartBodybuilder.build();
        }
    }

    /**
     * get，head...方法将参数和url 拼接
     *
     * @param url    请求url
     * @param params 请求参数
     * @return 拼接后 url
     */
    protected String appendParams(String url, ConcurrentHashMap<String, String> params) {
        if (url == null || params == null || params.isEmpty()) {
            return url;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(url + "?");
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
        }
        sb = sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 根据不同的请求方式和参数，生成不同的RequestBody
     */
    protected abstract RequestBody generateRequestBody();

    /**
     * 根据不同的请求方式，将RequestBody转换成Request对象
     */
    protected abstract Request buildRequest(RequestBody requestBody);

    protected RequestBody wrapRequestBody(RequestBody requestBody, final RequestCallBack callback) {
        return requestBody;
    }

    public RequestCall build() {
        return new RequestCall(this);
    }

    public Request generateRequest(RequestCallBack callback) {
        RequestBody requestBody = generateRequestBody();
        RequestBody wrappedRequestBody = wrapRequestBody(requestBody, callback);
        Request request = buildRequest(wrappedRequestBody);
        return request;
    }

}

